package com.sixth.core.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 李劲锋
 * @create: 2024-08-12 16:52
 **/
public class OSSUtil {
    public static String uploadOss(MultipartFile myfile){
        // 自己的endpoint
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        //bucketNname的名称
        String bucketName = "zql-01";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String filename = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        String objectName = filename; //上传到oss的名称

        String accessKeyId = "LTAI5t6FNgQNxZ48iYU2MfmM";
        String secretAccessKey = "eWSKxaTpDJJyt7taI1SJXrmOB1LONm";
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,secretAccessKey);
        try {
            ossClient.putObject(bucketName, objectName, myfile.getInputStream());
            return "https://"+bucketName+"."+endpoint+"/"+objectName;
        }  catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传失败，错误信息：" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "失败";

    }
    public static boolean deleteOss(String url) {
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String bucketName = "zql-01";
        String accessKeyId = "LTAI5t6FNgQNxZ48iYU2MfmM";
        String secretAccessKey = "eWSKxaTpDJJyt7taI1SJXrmOB1LONm";

        String objectName = url.substring(url.lastIndexOf("/") + 1); // 从URL中提取objectName

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);
        try {
            ossClient.deleteObject(bucketName, objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}